var AdminScriptEditor = {};

AdminScriptEditor.TinyMCE = null;
AdminScriptEditor.HasChanges = false;

/*----------------------------------------------------------------------*/
/* INIT */
AdminScriptEditor.Init = function(){
	this.ActivateTinyMCE($("#content > .scriptBlock .scriptText"));
	AdminScriptEditor.SetSortableOnDecisions($("ul.scriptDecisions"));

};

/*----------------------------------------------------------------------*/
/* INITHANDLERS */
AdminScriptEditor.InitHandlers = function () {

	/* scriptMenuItem Click */
	/*------------------------------*/
	$("DIV.scriptMenu BUTTON.scriptMenuItem").live("click", function (e) {

		AdminScriptEditor.HideScriptMenu();

		var $this = $(this);
		var thisMenu = $this.attr("menu");

		var $scriptMenuItemDropDown = $("DIV.scriptMenuItemDropDown[menu=" + thisMenu + "]");

		if ($this.hasClass("selected")) {
			$this.removeClass("selected");
			$scriptMenuItemDropDown.fadeOut("fast");
		}
		else {
			$this.addClass("selected");
			$scriptMenuItemDropDown.fadeIn("fast");
			$scriptMenuItemDropDown.position({
				my: "left top",
				at: "left bottom",
				of: this,
				offset: "5 -1"
			});
		}

		e.stopImmediatePropagation();
	});

	/* scriptMenu Click */
	/*-------------------------*/
	$(document).click(function (e) {
		AdminScriptEditor.HideScriptMenu();
		$("#categoryList").slideUp(100);
	});

	/* ******************************************************************* */
	/* ************************* MENU OPTION ***************************** */

	/*optSave click */
	/*-------------------------*/
	$("div.scriptMenuItemDropDown li.optSave").bind("click", function (e) {
		AdminScriptEditor.SaveScript();
	});

	/*optPreview click */
	/*-------------------------*/
	$("div.scriptMenuItemDropDown li.optPreview").bind("click", function (e) {
		AdminScriptEditor.PreviewScript();
	});

	/*optNew click */
	/*-------------------------*/
	$("div.scriptMenuItemDropDown li.optNew").bind("click", function (e) {
		if (AdminScriptEditor.HasChanges) {
			$("<div>You have unsaved changes to this script. If you go to a new script without saving then your changes will be lost.<br><br>Do you want to go to a new script anyway?</div>")
                .dialog({
                	modal: true,
                	width: 600,
                	buttons: {
                		"Yes": function () {
                			window.location.href = "AdminScriptEditor.asp";
                		},
                		"No": function () {
                			$(this).dialog("close");
                		}
                	},
                	title: "You Have Unsaved Changes",
                	close: function (e, ui) { }
                });
		}
		else {
			window.location.href = "AdminScriptEditor.asp";
		}
	});

	/*optOpen click */
	/*-------------------------*/
	$("div.scriptMenuItemDropDown li.optOpen").bind("click", function (e) {
		AdminScriptEditor.OpenDialog();
	});

	/*optExport click */
	/*-------------------------*/
	$("div.scriptMenuItemDropDown li.optExport").bind("click", function () {
		AdminScriptEditor.ExportDialog();
	});

	/*optImport click */
	/*-------------------------*/
	$("div.scriptMenuItemDropDown li.optImport").bind("click", function () {
		AdminScriptEditor.ImportDialog();
	});

	/*optScriptManager click */
	/*-------------------------*/
	$("div.scriptMenuItemDropDown li.optScriptManager").bind("click", function () {
		window.location = "AdminScriptManager.asp";
	});

	/* ************************ /MENU OPTIONS ************************ */
	/* *************************************************************** */



	/* *** BUTTONS *** */

	/* .scriptBlockMenu save button */
	/*-----------------------------------------*/
	$(".scriptBlockMenu .btnSave").live("click", function () {
		AdminScriptEditor.SaveTinyMCE();
	});

	/* scriptBlockMenu exit button */
	/*-----------------------------------*/
	$(".scriptBlockMenu .btnExit").live("click", function () {
		var scriptBlock = $(this).closest(".scriptBlock");
		AdminScriptEditor.DeactiveTinyMCE(scriptBlock);
	});

	/* scriptBlockMenu edit button */
	/*-----------------------------------*/
	$(".scriptBlockMenu .btnEdit").live("click", function () {
		if (tinymce.activeEditor != undefined) {
			var tinyMCEScriptBlock = $("#" + tinymce.activeEditor.id).closest(".scriptBlock");
			AdminScriptEditor.DeactiveTinyMCE(tinyMCEScriptBlock);
		}

		var scriptBlock = $(this).closest(".scriptBlock");
		AdminScriptEditor.ActivateTinyMCE(scriptBlock.find(">.scriptText"));
	});

	/* btnScriptCategoryArrow click */
	/*----------------------------------------------*/
	$("#btnScriptCategoryArrow").bind("click", function (e) {
		var categoryList = $("#categoryList");
		var txtScriptCategory = $("#txtScriptCategory");

		categoryList.slideToggle(100);

		categoryList.position({
			my: "left top",
			at: "left bottom",
			of: txtScriptCategory
		});

		categoryList.width(txtScriptCategory.outerWidth() - 2);
		var maxHeight = (($(window).height() - categoryList.position().top) - 10) + "px";

		categoryList.css({ "max-height": maxHeight });

		return false;
		e.preventDefault();
		e.stopImmediatePropagation(); //so that the document.click() doesnt trigger which would cause the dropdown to close

	});

	/* .btnAddNewDecision click */
	/*-------------------------*/
	$("ul.scriptDecisions").delegate("li.scriptDecision .btnAddNewDecision", "click", function () {
		var $this = $(this);
		var decisionBlock = $this.closest(".decisionBlock");

		AdminScriptEditor.CreateNewDecision(decisionBlock);
	});

	/* .btnDelete click */
	/*-------------------------*/
	$("ul.scriptDecisions").delegate("li.scriptDecision .btnDelete", "click", function () {
		var btnDelete = $(this);
		var decisionTitle = btnDelete.siblings(".decisionTitle");
		var decisionTitleText = (decisionTitle.children("input").length > 0 ? decisionTitle.children("input:first").val() : decisionTitle.html());
		var dlgText = "Are you sure you want to DELETE Decision: '<b>" + decisionTitleText + "</b>'?<br><br>"
            + "Doing so will also delete every associated Text and Decision, and the action will NOT be able to be undone.";

		$("body").append("<div id='dlgDecisionDelete'>" + dlgText + "</div>");

		var dlgBody = $("#dlgDecisionDelete").dialog({
			modal: true,
			width: 600,
			buttons: {
				"Yes": function () {
					var decision = btnDelete.closest(".scriptDecision");
					var dlgButtonPane = $(this).siblings(".ui-dialog-buttonpane");
					var dlg = dlgBody.closest(".ui-dialog");

					AdminScriptEditor.DeleteDecision(decision, dlg);
				},
				"No": function () {
					$(this).dialog("close");
				}
			},
			title: "Confirm Delete",
			close: function (e, ui) { $("#dlgDecisionDelete").remove(); }
		});
	});

	/* dlgImport Cancel button click */
	/*-----------------------------------------*/
	$("#dlgImport_btnCancel").live("click", function () {
		$("#dlgImport").dialog("close");
	});

	/* dlgImport Import button click */
	/*-----------------------------------------*/
	$("#dlgImport_btnImport").live("click", function () {
		var fileInput = $("#dlgImport_scriptFile");
		var fileInputName = String(fileInput.val());
		var content = $("#dlgImport_Content");
		var fileExtension;
		var fileInputNameArray;
		var validated = true;


		/* validate */
		if (fileInputName != "") {

			fileInputNameArray = fileInputName.replace(/\\/g, "/").split("/");
			fileInputName = fileInputNameArray.pop(); //gets last element in array

			fileExtension = fileInputName.split(".").pop();

			if (fileExtension.toLowerCase() != "script") {
				alert("'" + fileInputName + "' is not a .SCRIPT file.\n This import function only works with .SCRIPT files.");
				fileInput.val("");

				validated = false;
			}
		}
		else {
			alert("You must select a file before clicking Import.");

			validated = false;
		}

		/* /validate */


		if (!validated) return false;


		/* please wait */
		content.find("div.status").remove(); //in case this is a repeat attempt with the same dialog, remove the previous status div
		content.showWhiteSquareWaiting(
            {
            	container: "#dlgImport_Content",
            	callback: function () {
            		var content = $("#dlgImport_Content");
            		var form = content.find("FORM:first");

            		/* change form action and submit to iframe */
            		form[0].action = "AdminScriptEditorFileUpload.asp";
            		form.submit();
            	}
            }
        );




	});

	/* *** /BUTTONS *** */



	/* dlgImport File Input onChange */
	/*-----------------------------------------*/
	$("#dlgImport_scriptFile").live("click", function () {



	});

	/*#txtScriptCategory #txtScriptTitle change*/
	/*--------------------------------------------*/
	$("#txtScriptCategory, #txtScriptTitle").bind("change", function () {
		AdminScriptEditor.SetHasChanges(true, "script");
	});

	/*.iconExpandCollapse click */
	/*---------------------------*/
	$("ul.scriptDecisions").delegate("li.scriptDecision .iconExpandCollapse", "click", function () {
		var $this = $(this);

		var scriptBlock = $this.siblings("div.scriptBlock");
		var scriptTitle = $this.siblings(".decisionTitle");

		if ($this.hasClass("decisionExpand")) {
			scriptBlock.slideDown("fast", function () {

				$this.removeClass("decisionExpand");
				$this.addClass("decisionCollapse");

			});

			if (scriptBlock.hasClass("loading")) {
				AdminScriptEditor.LoadExistingDecision(scriptBlock);
			}
		}
		else {
			scriptBlock.slideUp("fast", function () {

				$this.removeClass("decisionCollapse");
				$this.addClass("decisionExpand");

			});
		}
	});

	/* .decisionTitle click */
	/*---------------------------*/
	$("ul.scriptDecisions").delegate("li.scriptDecision .decisionTitle", "click", function () {
		var $this = $(this);

		$this.siblings(".iconExpandCollapse").trigger("click");

	});

	/* txtDecisionTitle click */
	/*------------------------*/
	$("ul.scriptDecisions").delegate("li.scriptDecision  .decisionTitle input.txtDecisionTitle", "click", function (e) {
		/* the whole purpose of this handler is to prevent clicking on the input box from bubbling up to its parent 
		* container's (.decisionTitle) click event handler which causes the decision LI to collapse (.slideUp()) */

		e.stopImmediatePropagation();
	});

	/* .decisionBlockLabelExpandCollapse click */
	/*---------------------------*/
	$("div.scriptBlock").delegate(".decisionBlockLabelExpandCollapse", "click", function () {
		var $this = $(this);
		var decisionUL = $this.siblings("ul.scriptDecisions");

		if ($this.hasClass("decisionBlockLabelExpand")) {
			decisionUL.find("> li").each(function () {
				$(this).slideDown("fast");
			});

			$this.removeClass("decisionBlockLabelExpand");
			$this.addClass("decisionBlockLabelCollapse");
		}
		else {
			decisionUL.find("> li").each(function () {
				$(this).slideUp("fast");
			});

			$this.removeClass("decisionBlockLabelCollapse");
			$this.addClass("decisionBlockLabelExpand");


		}
	});

	/* .decisionBlockLabel click */
	/*---------------------------*/
	$("div.decisionBlock").delegate(".decisionBlockLabel", "click", function (e) {
		var $this = $(this);

		$this.siblings(".decisionBlockLabelExpandCollapse").trigger("click");

	});

	/* applianceExpand click */
	/*----------------------------------------------*/
	$("#applianceExpand").bind("click", function (e) {
		var applianceExpand = $(this);

		applianceExpand.toggleClass("ui-icon-circlesmall-plus ui-icon-circlesmall-minus");
		$("#categoryApplianceList").slideToggle(100);

		return false;
		e.preventDefault();
		e.stopImmediatePropagation(); //so that (#applianceLabel).click() doesn't trigger which would cause the appliance list to close
	});

	/* categoryApplianceList click */
	/*----------------------------------------------*/
	$("#applianceLabel").bind("click", function (e) {
		$("#applianceExpand").toggleClass("ui-icon-circlesmall-plus ui-icon-circlesmall-minus");
		$("#categoryApplianceList").slideToggle(100);


		return false;
		e.preventDefault();
		e.stopImmediatePropagation(); //so that the document.click() doesnt trigger which would cause the dropdown to close
	});

	/* categoryList LI click */
	/*----------------------------------------------*/
	$("#categoryList li").bind("click", function (e) {
		var li = $(this);
		var val = li.attr("val");

		$("#txtScriptCategory").val(val);

		AdminScriptEditor.SetHasChanges(true, "script");
	});

	/* txtScriptTitle key up */
	/*----------------------------------------------*/
	$("#txtScriptTitle").bind("keyup", function (e) {

		AdminScriptEditor.ValidateTitle();
	});

	/* dlgOpenScript_SelectableRow click */
	/*----------------------------------------------*/
	$(".dlgOpenScript_SelectableRow").live("click", function (e) {
		var scriptID = this.getAttribute("scriptid");

		$("#dlgOpenScript").showWhiteSquareWaiting(
            {
            	callback: function () {
            		var cacheBusterDate = new Date();
            		var cacheBuster = "";
            		cacheBuster +=
						(cacheBusterDate.getDate().toString()
						+ cacheBusterDate.getMonth().toString()
						+ cacheBusterDate.getFullYear().toString()
						+ cacheBusterDate.getHours().toString()
						+ cacheBusterDate.getMinutes().toString()
						+ cacheBusterDate.getSeconds().toString());

            		var url = "AdminScriptEditor.asp?scriptid=" + scriptID + "&d=" + cacheBuster;
            		location.href = url;
            	}
            }
        );


	});

};


/* END INITHANDLER */




/*----------------------------------------------------------------------*/
/* VALIDATE TITLE */
AdminScriptEditor.ValidateTitle = function(){

    var txtScriptTitle = $("#txtScriptTitle");
    var titleErrorMsg = $("#titleErrorMsg");
    
    if(txtScriptTitle.val().length < 3){
        $("#titleSection")
            .removeClass("titleOK")
            .addClass("titleInvalid");
        
        if(txtScriptTitle.val().length == 0){
            titleErrorMsg.html("Title Cannot Be Empty.");
        }
        else{
            titleErrorMsg.html("Title Must Be A Minimum Of 3 Characters.");
        }
        
        titleErrorMsg.fadeIn();
        
        return false;
    }
    
    if(txtScriptTitle.val() == txtScriptTitle.attr("originalvalue")){
        $("#titleSection")
            .removeClass("titleInvalid")
            .addClass("titleOK");
        
        titleErrorMsg.faceOut();
        
        return false;  
    }
    
    
    
    var onSuccess = function(response){
		if(response.Success){
		    if(response.Data > 0){
                $("#titleSection")
                    .removeClass("titleOK")
                    .addClass("titleInvalid");
                
                titleErrorMsg
                    .html("Title: <em>'" + txtScriptTitle.val() + "'</em> Already Exists For Another Script. Titles Must Be Unique.")
                    .fadeIn();        
		    }
		    else{
                $("#titleSection")
                    .removeClass("titleInvalid")
                    .addClass("titleOK");
                
                titleErrorMsg.fadeOut();		    
		    }
		}
		else{}
    };
        
    var onError = function(jqXHR, textStatus, errorThrown) {
    };

    var onComplete = function() {
        AdminScriptEditor.ActiveTitleSearch = null;
    };	
	
	
	
	
	if(AdminScriptEditor.ActiveTitleSearch != null){
	    AdminScriptEditor.ActiveTitleSearch.abort();
	}
	
	AdminScriptEditor.ActiveTitleSearch = $.ajax({
		url:		"AJAX/AdminScriptEditor.asp?method=SearchForTitles",
		type: 		"POST",
		success:	onSuccess,
        error:      onError,
        complete:   onComplete,
		data:		{
                        title: txtScriptTitle.val()
					}
	});
};

/*----------------------------------------------------------------------*/
/* IMPORT DIALOG */
AdminScriptEditor.ImportDialog = function () {

	var html = [
        "<div id='dlgImport'>",
            "<div id='dlgImport_Content' class=''>",
				"<form method='POST' action='' enctype='multipart/form-data' target='dlgImport_Iframe'>", //target='dlgImport_Iframe'
					"<label class='caption'>Select a .SCRIPT file to import:</label>",
					"<br/>",
					"<input type='file' name='dlgImport_scriptFile' id='dlgImport_scriptFile' />",
				"</form>",
				"<iframe name='dlgImport_Iframe' id='dlgImport_Iframe' ></iframe>",
				"<span class='btnContainer'>",
					"<button id='dlgImport_btnImport'>Import</button>",
					"<button id='dlgImport_btnCancel'>Cancel</button>",
				"</span>",
			"</div>",
        "</div>"
    ];

	$(html.join(""))
        .dialog({
        	modal: true,
        	width: 400,
        	title: "Import Script",
        	close: function (e, ui) {
        		var dlg = $(this).closest(".ui-dialog")
        		dlg.remove();
        		$("#dlgImport").remove();
        	}
        });

	var dlg = $("#dlgImport");
    var dlgContent = $("#dlgImport_Content");


};

/*----------------------------------------------------------------------*/
/* IMPORT ROUTINE ON-COMPLETE CALLBACK */
AdminScriptEditor.ImportDialogOnComplete = function (response) {

	var dlg = $("#dlgImport_Content");

	dlg.removeWhiteSquareWaiting();

	if (response && response.Success == true) {
		dlg.find("FORM").append("<div class='status success'>Script Successfully Imported!</div>");
	}
	else {
		dlg.find("FORM").append("<div class='status failed'>Script import failed for the following reason:<br>&nbsp;&nbsp;- " + response.ErrorMsg + "</div>");
	}
};

/*----------------------------------------------------------------------*/
/* EXPORT DIALOG */
AdminScriptEditor.ExportDialog = function(){

    var scriptid = $("#content").attr("scriptid");
    
    if(scriptid == "new" || scriptid == ""){
        alert("Cannot export a New script. In order to Export this script, please Save this New script first.");
        return false;
    }
	

    var html = [
        "<div id='dlgExport'>",
            "<div id='dlgExport_Content' class='whiteSquareWaiting'></div>",
        "</div>"
    ];
    
    $(html.join(""))
        .dialog({
            modal: true,
            width: 800,
            title: "Export Script",
            close: function(e, ui) { 
                var dlg = $(this).closest(".ui-dialog")
                dlg.remove();
                $("#dlgExport").remove();
            }                   
        });
    
    var dlg = $("#dlgExport");
    var dlgContent = $("#dlgExport_Content");
    
    var onSuccess = function(response){
		if(response.Success){
			html = [
				"<iframe name='dlgExport_iframe' id='dlgExport_iframe'></iframe>",
				"<form method='POST' action='AdminScriptEditorExport.asp' target='dlgExport_iframe'>",
					"<input type='hidden' name='json' value='" + response.Data.Script + "' />",
					"<input type='hidden' name='fileName' value='" + response.Data.FileName + "' />",
				"</form>"
			];
			
			dlgContent.html(html.join(""));
			dlgContent.find("form").submit();
			
			setTimeout(function(){dlg.dialog("close");}, 1000);
			
		}
		else{
	        alert("Failed to export script. Please close the Export Scripts dialog and try again. If the Export Scripts dialog continues to fail then please report it with this information:\n" +
				"Error: " + data.ErrorMessage);
		}
	};



    var onError = function(jqXHR, textStatus, errorThrown) {
        alert("Failed to export script. Please close the Export Scripts dialog and try again. If the Export Scripts dialog continues to fail then please report it with this information:\n" +
				"Error: " + errorThrown);
    };
	
	
    var onComplete = function() {
        //dlgContent.removeClass("whiteSquareWaiting");
    };
    

	$.ajax({
		url:		"AJAX/AdminScriptEditor.asp?method=ExportScript",
		type: 		"POST",
		success:	onSuccess,
        error:      onError,
        complete:   onComplete,
		data:		{
						ScriptID: scriptid
					}
	});
	
};

/*----------------------------------------------------------------------*/
/* PREVIEW DIALOG */
AdminScriptEditor.PreviewScript = function(){

    var scriptid = $("#content").attr("scriptid");
    
    if(scriptid == "new" || scriptid == ""){
        alert("Cannot preview a New script. In order to Preview this script, please Save this New script first.");
        return false;
    }

    var cacheBusterDate = new Date();
    var cacheBuster = "";
    cacheBuster +=
					(cacheBusterDate.getDate().toString()
					+ cacheBusterDate.getMonth().toString()
					+ cacheBusterDate.getFullYear().toString()
					+ cacheBusterDate.getHours().toString()
					+ cacheBusterDate.getMinutes().toString()
					+ cacheBusterDate.getSeconds().toString());

    var html = [
        "<div id='dlgPreviewScript'>",
            "<div id='dlgPreviewScript_PleaseWait' class='whiteSquareWaiting'></div>",
            "<iframe id='dlgPreviewScript_content' class='hidden' src='ScriptReader.asp?scriptid=" + scriptid + "&d=" + cacheBuster + "'></iframe>",
        "</div>"
    ];
    
    $(html.join(""))
        .dialog({
            modal:  true,
            width:  800,
            height: 500,
            title:  "Preview Script",
            close:  function(e, ui) { 
                var dlg = $(this).closest(".ui-dialog")
                dlg.remove();
                $("#dlgPreviewScript").remove();
            }                   
        });
    
};

/*----------------------------------------------------------------------*/
/* OPEN DIALOG */
AdminScriptEditor.OpenDialog = function() {
    var html = [
        "<div id='dlgOpenScript'>",
            "<div id='dlgOpenScript_ListContainer' class='whiteSquareWaiting'></div>",
        "</div>"
    ];
    
    $(html.join(""))
        .dialog({
            modal: true,
            width: 800,
            title: "Open Script",
            close: function(e, ui) { 
                var dlg = $(this).closest(".ui-dialog")
                dlg.remove();
                $("#dlgOpenScript").remove();
            }                   
        });
    
    var dlg = $("#dlgOpenScript");
    var listContainer = $("#dlgOpenScript_ListContainer");
    
    
    
    var onSuccess = function(response){
		if(response.Success){
			var html = ["<table cellspacing='0' cellpadding='0'>"];
			var headers = response.Data.Headers;
			var scripts = response.Data.Scripts;
			
			html.push("<tr>");
			for(var x = 0, len = headers.length; x < len; x++){
			    var sorted = "";
			    
			    if(headers[x].toLowerCase() != "scriptid"){
			        if(headers[x].toLowerCase() == "title"){
			            sorted="sorted";
			        }
			        
			        html.push("<th class='", sorted, "'>", headers[x], "</th>");
			    }
			};
			html.push("</tr>");
			
			if(scripts.length > 0){
			    for(var x = 0, len = scripts.length; x < len; x++){
			        var curScript = scripts[x];
			        var created = new Date(curScript.Created);
			        var modified = (curScript.Modified != "null" ? new Date(curScript.Modified) : "--");
			        
			        html.push(
			            "<tr scriptid='", curScript.ScriptID, "' class='dlgOpenScript_SelectableRow' scriptid='" + curScript.ScriptID + "' >",
			                "<td>",
			                    curScript.Category,
			                "</td>",
			                "<td>",
			                    curScript.Title,
			                "</td>",
			                "<td>",
			                    (created.getMonth() + 1), "/", created.getDate(), "/", created.getFullYear(),
			                "</td>",
			                "<td>",
			                    curScript.CreatedBy,
			                "</td>",
			                "<td>",
			                    (modified != "--"
			                        ? (modified.getMonth() + 1) + "/" + (modified.getDate() + "/" + modified.getFullYear())
			                        : "--"),
			                "</td>",
			                "<td>",
			                    curScript.ModifiedBy,
			                "</td>",
			            "</tr>"
			        );
			    };
			}
			else{
			    html.push(
			        "<tr>",
			            "<td colspan='", (headers.length - 1), "'>",
			                "No Scripts Found",
			            "</td>",
			        "</tr>"
			    );
			}
			
			html.push("</table>");
			
			listContainer.html(html.join(""));
			
		}
		else{
	        alert("Failed to retrieve list of scripts. Please close the Open Scripts dialog and try again. If the Open Scripts dialog continues to fail then please report it with this information:\n" +
				"Error: " + data.ErrorMessage);
		}
	};

    var onError = function(jqXHR, textStatus, errorThrown) {
        alert("Failed to retrieve list of scripts. Please close the Open Scripts dialog and try again. If the Open Scripts dialog continues to fail then please report it with this information:\n" +
				"Error: " + errorThrown);
    };

    var onComplete = function() {
        listContainer.removeClass("whiteSquareWaiting");
    };	
	
	$.ajax({
		url:		"AJAX/AdminScriptEditor.asp?method=GetScripts",
		type: 		"POST",
		success:	onSuccess,
        error:      onError,
        complete:   onComplete,
		data:		{

					}
	});
}

/*----------------------------------------------------------------------*/
/* DELETE DECISION */
AdminScriptEditor.DeleteDecision = function(decision, dlg) {
    var decisionID = decision.attr("decisionid");
    var btnPane = dlg.children(".ui-dialog-buttonpane");

    if (dlg) {
        var pleaseWait = btnPane.siblings(".dlgPleaseWait");

        if (pleaseWait.length == 0) {
            pleaseWait = $("<span class='dlgPleaseWait'>Deleting. Please Wait...<span class='waitingSpinnerSmall'></span></span>");

            dlg.append(pleaseWait);
        }

    }

    var onSuccess = function(response) {
        if (response.Success) {
            decision.remove();
            dlg.find(".ui-dialog-titlebar-close").trigger("click");
        }
        else {
            alert("Decision failed to delete. Please try again. If this Decision continues to fail to delete then please report it with this information:\n" +
					"Script ID: " + $("#content").attr("scriptid") + "\n" +
					"Dicision ID: " + decisionID + "\n" +
					"Error: " + response.ErrorMessage);
        }
    };

    var onError = function(jqXHR, textStatus, errorThrown) {
        alert("Decision failed to delete. Please try again. If this Decision continues to fail to delete then please report it with this information:\n" +
				"Script ID: " + $("#content").attr("scriptid") + "\n" +
				"Dicision ID: " + decisionID + "\n" +
				"Error: " + errorThrown);
    };

    var onComplete = function() {
        pleaseWait.slideUp("fast", function() {
            btnPane.slideDown("fast");
        });
    };

    btnPane.slideUp("fast", function() {
        pleaseWait.slideDown("fast");

        $.ajax({
            url:        "AJAX/AdminScriptEditor.asp?method=DeleteDecision",
            type:       "POST",
            success:    onSuccess,
            error:      onError,
            complete:   onComplete,
            data:       {
                            DecisionID: decisionID
                        }
        });
    });


};

/*----------------------------------------------------------------------*/
/* SET SORTABLE ON DECISIONS */
AdminScriptEditor.SetSortableOnDecisions = function(scriptDecisions){
	scriptDecisions.sortable({
		items: 			">:not(.addNew)",
		containment:	scriptDecisions.closest(".decisionBlock"),
		axis:			"y",
		stop:			AdminScriptEditor.SaveDecisionOrder
	});
};

/*----------------------------------------------------------------------*/
/* SAVE DECISION ORDER */
AdminScriptEditor.SaveDecisionOrder = function(e, ui){
	var order = 		[];
	var decisions = 	$(this).children("li:not(.addNew)");
	var scriptBlockID = $(this).closest(".scriptBlock").attr("scriptblockid");
	
	for(var x = 0, len = decisions.length; x < len; x++){
		var curDecision = $(decisions[x]);
		
		order.push(curDecision.attr("decisionid"));
	}
	
	var onSuccess = function(response){
		if(response.Success){
			
		}
		else{
			
		}
	};
	
	$.ajax({
		url:		"AJAX/AdminScriptEditor.asp?method=SaveDecisionOrder",
		type: 		"POST",
		success:	 onSuccess,
		data:		{
						ScriptBlockID: 	scriptBlockID,
						Order:			order.join(",")
					}
	});
};

/*----------------------------------------------------------------------*/
/* LOAD EXISTING DECISION */
AdminScriptEditor.LoadExistingDecision = function(scriptBlock){
	var scriptBlockID = 	scriptBlock.attr("scriptblockid");
	var scriptDecision = 	scriptBlock.parent();

	var onSuccess = function(response){
		if(!response.Success){
			alert("Failed to load Script. Please try collapsing and expanding this Decision again.\n If loading continues to fail then please report it.\n\nError: " + response.ErrorMessage);
			scriptBlock.siblings(".iconExpandCollapse").trigger("click");
			return false;
		}
		
		var newDecisionID = 	response.Data.DecisionID;
		var newScriptBlockID = 	response.Data.ScriptBlockID;
		var newScriptText = 	response.Data.ScriptText;
		
		var template = AdminScriptEditor.BuildScriptBlockHTML(newDecisionID, newScriptBlockID, newScriptText)
		var newScriptBlock = $(template);
		
		scriptBlock.remove();
		scriptDecision.append(newScriptBlock);
		newScriptBlock.removeClass("hidden");
		
		var breadCrumb = newScriptBlock.find(".breadCrumb");
		breadCrumb.html(AdminScriptEditor.CreateBreadCrumb(breadCrumb));
		
		/* iterate decisions and build empty decisions */
		var html = [], curDecision, DecisionID, ScriptBlockID, DecisionTitle, ChildScriptBlockID;

		for(var x = 0, len = response.Data.Decisions.length; x < len; x++){
			curDecision = response.Data.Decisions[x];
			
			DecisionID =			curDecision.DecisionID;
			ScriptBlockID =			curDecision.ScriptBlockID;
			DecisionTitle = 		curDecision.DecisionTitle;
			ChildScriptBlockID =	curDecision.ChildScriptBlockID;
			
			html.push(AdminScriptEditor.BuildEmptyDecisionHTML(DecisionID, ScriptBlockID, DecisionTitle, ChildScriptBlockID));
		}
		
		var scriptDecisions = newScriptBlock.find("ul.scriptDecisions");
		
		scriptDecisions.prepend(html.join(""));
		
		AdminScriptEditor.SetSortableOnDecisions(scriptDecisions);
	};
	/* end onSuccess */

	var onError = function(jqXHR, textStatus, errorThrown){
		alert("Failed to load Script. Please try collapsing and expanding this Decision again.\n If loading continues to fail then please report it.\n\nError: " + errorThrown);
		
		scriptBlock.siblings(".iconExpandCollapse").trigger("click");
	};
	
	var onComplete = function(jqXHR, textStatus){
		
	};
	
	
	$.ajax({
		url:		"AJAX/AdminScriptEditor.asp?method=LoadExistingDecision",
		type: 		"POST",
		success: 	onSuccess,
		error: 		onError,
		complete: 	onComplete,
		data:		{
						ScriptBlockID: scriptBlockID
					}
	});	
};

/*----------------------------------------------------------------------*/
/* CREATE NEW DECISION */
AdminScriptEditor.CreateNewDecision = function(decisionBlock){

	var scriptDecisions = 		decisionBlock.find("> .scriptDecisions");
	var btnAddNewLI =			scriptDecisions.find("> li.addNew");
	var parentScriptBlock = 	decisionBlock.closest(".scriptBlock");
	var parentScriptBlockID = 	parentScriptBlock.attr("scriptblockid");
	var scriptID = 				$("#content").attr("scriptid");
	var order = 				scriptDecisions.find("li:not(.addNew)").length;
	
	
	var onSuccess = function(response){
		if(!response.Success){
			alert("Failed to create new Decision. Please try again.\n if saving continues to fail then please report it.\n\nError: " + response.ErrorMessage);
			return false;
		}
		
		var newDecisionID = 	response.Data.NewDecisionID;
		var newDecisionTitle = 	response.Data.NewDecisionTitle;
		var newScriptBlockID = 	response.Data.NewScriptBlockID;
		var newScriptText = 	response.Data.NewScriptText;

		var template = 			AdminScriptEditor.BuildDecisionHTML(newDecisionID, parentScriptBlockID, newScriptBlockID, newDecisionTitle, newScriptText)
		
		var newDecision = 		$(template);
		
		btnAddNewLI.before(newDecision);
		
		var breadCrumb = newDecision.find(".breadCrumb");
		breadCrumb.html(AdminScriptEditor.CreateBreadCrumb(breadCrumb));
		
		AdminScriptEditor.SetSortableOnDecisions(scriptDecisions);	
	};
	
	
	var onError = function(jqXHR, textStatus, errorThrown){
		alert("Failed to create new Decision. Please try again.\n if saving continues to fail then please report it.\n\nError: " + errorThrown);
	};
	
	var onComplete = function(jqXHR, textStatus){
		
	};
	
	
	$.ajax({
		url:		"AJAX/AdminScriptEditor.asp?method=SaveNewDecision",
		type: 		"POST",
		success: 	onSuccess,
		error: 		onError,
		complete: 	onComplete,
		data:		{
						ScriptID: 		scriptID,
						ScriptBlockID: 	parentScriptBlockID,
						Order:			order
					}
	});	
	
};

/*----------------------------------------------------------------------*/
/* BUILD DECISION HTML */
AdminScriptEditor.BuildDecisionHTML = function(newDecisionID, parentScriptBlockID, newScriptBlockID, newDecisionTitle, newScriptText){
	var template = $("#decisionTemplate").html();
	var scriptBlockTemplate = AdminScriptEditor.BuildScriptBlockHTML(newDecisionID, newScriptBlockID, newScriptText);

	template = template.replace(/\{newdecisionid\}/gi, newDecisionID);
	template = template.replace(/\{parentscriptblockid\}/gi, parentScriptBlockID);
	template = template.replace(/\{newscriptblockid\}/gi, newScriptBlockID);
	template = template.replace(/\{NewDecisionTitle\}/gi, newDecisionTitle);
	template = template.replace(/\{NewScriptText\}/gi, newScriptText);
	template = template.replace(/\{scriptBlockTemplate\}/gi, scriptBlockTemplate);
	
	return template;
}

/*----------------------------------------------------------------------*/
/* BUILD SCRIPT BLOCK HTML */
AdminScriptEditor.BuildScriptBlockHTML = function(newDecisionID, newScriptBlockID, newScriptText){
	var template = $("#scriptBlockTemplate").html();
	
	template = template.replace(/\{newdecisionid\}/gi, newDecisionID);
	template = template.replace(/\{newscriptblockid\}/gi, newScriptBlockID);
	template = template.replace(/\{NewScriptText\}/gi, newScriptText);
	
	return template;
}

/*----------------------------------------------------------------------*/
/* BUILD EMPTY DECISION HTML */
AdminScriptEditor.BuildEmptyDecisionHTML = function(DecisionID, ScriptBlockID, DecisionTitle, ChildScriptBlockID){
	var template = $("#emptyDecisionTemplate").html();
	
	template = template.replace(/\{DecisionID\}/gi, DecisionID);
	template = template.replace(/\{ScriptBlockID\}/gi, ScriptBlockID);
	template = template.replace(/\{DecisionTitle\}/gi, DecisionTitle);
	template = template.replace(/\{ChildScriptBlockID\}/gi, ChildScriptBlockID);
	
	return template;
}

/*----------------------------------------------------------------------*/
/* ACTIVATE TINYMCE */
AdminScriptEditor.ActivateTinyMCE = function(scriptText){
	
	scriptText.tinymce({
		script_url:	 						'Content/Scripts/tiny_mce/tiny_mce.js',
		theme:		 						"advanced",
		skin:								"o2k7",
		skin_variant:						"silver",
		plugins: 							"style,table,advlink,inlinepopups,preview,contextmenu,paste,visualchars,nonbreaking,advlist",
		oninit:					 			function(){
												var tinyMCE = $("#" + tinymce.activeEditor.id + "_parent");
						
												tinyMCE.css("width", "100%");
												tinyMCE.find(">table, td.td.mceIframeContainer, iframe")
													.css("width", "100%");
											},
	    setup :                             function(ed) {
                                                ed.onChange.add(function(ed, l) {
                                                    if(tinymce.activeEditor.isDirty()){
                                                        AdminScriptEditor.SetHasChanges(true, "tinymce");
                                                    }
                                                    else{
                                                        AdminScriptEditor.SetHasChanges(false, "tinymce");
                                                    }
                                                });


                                             },

		// Theme options
		theme_advanced_buttons1: 			"cut,copy,paste,pastetext,pasteword,|,undo,redo,|,|,cleanup,code,preview,|,visualaid,visualchars,nonbreaking,removeformat,styleprops",
		theme_advanced_buttons2: 			"bold,italic,underline,sub,sup,|,fontselect,fontsizeselect,forecolor,backcolor,|,justifyleft,justifycenter,justifyright,justifyfull",
		theme_advanced_buttons3: 			"bullist,numlist,|,outdent,indent,|,link,unlink,|,charmap,hr,|,tablecontrols",
		theme_advanced_toolbar_location: 	"top",
		theme_advanced_toolbar_align: 		"left",
		theme_advanced_statusbar_location: 	"bottom",
		theme_advanced_resizing: 			true
		//theme_advanced_resize_horizontal : false
	});
	
	var scriptBlock =       scriptText.closest(".scriptBlock");
	var scriptBlockMenu = 	scriptText.siblings(".scriptBlockMenu");
	var scriptDecision = 	scriptBlockMenu.closest(".scriptDecision");

	if(scriptDecision.length > 0){
		var decisionTitle = 	scriptDecision.find(">.decisionTitle")
		var decisionTitleText = decisionTitle.html();
		
		scriptDecision.addClass("editMode");
		
		decisionTitle.html("<label>Decision Title:</label>&nbsp;" +
		    "<input type='text' class='txtDecisionTitle' currentvalue='" + decisionTitleText + "' value='" + decisionTitleText + "'/>");
	}
	
	scriptBlock.addClass("editMode");
	
	scriptBlockMenu.children("button").each(function(){
		var $this = $(this);
		if($this.hasClass("btnEdit"))
			$this.addClass("hidden");
			
		if($this.hasClass("btnSave"))
			$this.removeClass("hidden");
		
		if($this.hasClass("btnExit"))
			$this.removeClass("hidden");
	});
	
};

/*----------------------------------------------------------------------*/
/*	DECACTIVATE TINYMCE */
AdminScriptEditor.DeactiveTinyMCE = function(scriptBlock){
	tinyMCE.execCommand('mceRemoveControl', false, tinymce.activeEditor.id);
	
	var scriptBlockMenu = 	scriptBlock.find(">.scriptBlockMenu");
	var scriptDecision = 	scriptBlockMenu.closest(".scriptDecision");
	
	if(scriptDecision.length > 0){
		var decisionTitle = 	scriptDecision.find(">.decisionTitle")
		var decisionTitleText = decisionTitle.find(">input:first").attr("currentvalue");		
		
		scriptDecision.removeClass("editMode");

		decisionTitle.html(decisionTitleText);
	}
	
	scriptBlock.removeClass("editMode");
	
	scriptBlockMenu.children("button").each(function(){
		var $this = $(this);
		if($this.hasClass("btnEdit"))
			$this.removeClass("hidden");
			
		if($this.hasClass("btnSave"))
			$this.addClass("hidden");
		
		if($this.hasClass("btnExit"))
			$this.addClass("hidden");
	});
	
	
}

/*----------------------------------------------------------------------*/
/* SAVE TINYMCE */
AdminScriptEditor.SaveTinyMCE = function(){
	var scriptID = 		$("#content").attr("scriptid");
	
	if(scriptID == "new"){
		alert("The script has not been saved yet. You must save the script first before attempting to save this script block.");
		return false;
	}	
	
	var scriptBlock = 	$("#" + tinymce.activeEditor.id).closest(".scriptBlock");
	var scriptBlockID = scriptBlock.attr("scriptblockid");
	var decision =      scriptBlock.closest(".scriptDecision");
	var decisionID =    scriptBlock.attr("parentdecisionid");
	var decisionTitle = scriptBlock.siblings(".decisionTitle").find("input:first").val();
	
	if(scriptID == ""
		|| scriptBlockID == ""
		|| decisionID == ""){
		
			alert("Script Block cannot be saved due to missing internal parameters");	
			return false;
	}
	
	if(decisionTitle == "")
	{
	    alert("Script Block cannot be saved because Decision Title cannot be blank.");
	    return false;
	}
	
	var parent = scriptBlock.find("#" + tinymce.activeEditor.id + "_parent");
	parent.showWhiteSquareWaiting();
	
	
	var onSuccess = function(response){
			if(response.Success){
				scriptBlock.attr("scriptblockid", response.Data);
				scriptBlock.siblings(".decisionTitle").find("input:first").attr("currentvalue", decisionTitle);
			    AdminScriptEditor.CreateBreadCrumbChain(decision);
			    AdminScriptEditor.SetHasChanges(false, "tinymce");
			}
			else{
				alert(response.ErrorMessage);
			}
	};
	
	var onError = function(jqXHR, textStatus, errorThrown){
			alert("Script Block failed to save. Please try again.\n if saving continues to fail then please report it.\n\nError: " + errorThrown);
	};
	
	var onComplete = function(jqXHR, textStatus){
		$("body").removeWhiteSquareWaiting();
	};
	

	$.ajax({
		url:		"AJAX/AdminScriptEditor.asp?method=SaveScriptBlock",
		type: 		"POST",
		success: 	onSuccess,
		error: 		onError,
		complete: 	onComplete,
		data:		{
						ScriptID:       scriptID,
						ScriptBlockID:  scriptBlockID,
						DecisionID:     decisionID,
						DecisionTitle: decisionTitle,
						ScriptText:     tinymce.activeEditor.getContent()
					}
	});
	
};

/*----------------------------------------------------------------------*/
/* HIDE THE DROPDOWN MENU */
AdminScriptEditor.HideScriptMenu = function(){
		var menuItem = 					$(".scriptMenuItem.selected").removeClass("selected"); 
		var $scriptMenuItemDropDown = 	$(".scriptMenuItemDropDown");

		$scriptMenuItemDropDown.fadeOut("fast");
};

/*----------------------------------------------------------------------*/
/* SAVE SCRIPT */
AdminScriptEditor.SaveScript = function () {
	var scriptID = $("#content").attr("scriptid");
	var category = $("#txtScriptCategory").val();
	var title = $("#txtScriptTitle").val();

	if (title == "") {
		alert("title cannot be blank.");
		return false;
	}

	if ($("#titleSection").hasClass("titleInvalid")) {
		alert($("#titleErrorMsg").text());
		return false;
	}

	if (category == "") {
		alert("category cannot be blank.");
		return false;
	}



	var onSuccess = function (response) {
		if (response.Success) {
			var content = $("#content");

			content.attr("scriptid", response.Data);
			$("ul.scriptDecisions li.addNew").removeClass("hidden");
			AdminScriptEditor.SetHasChanges(false, "script");

			var firstDecisionBlockUL = content.find("> .scriptBlock > .decisionBlock > UL");
			if (firstDecisionBlockUL.children("li.addNew").length == 0) {
				firstDecisionBlockUL.append(
				        "<li class='scriptDecision addNew'>" +
                            "<button class='btnAddNewDecision'>Add New Decision</button>" +
                        "</li>"
				    );
			}


			/* if this was a new script then a new primary scriptblockID should have been returned too. if it was then find the first scriptBlock and set its id */
			if (response.NewScriptBlockID) {
				content.find("> .scriptBlock").attr("scriptblockid", response.NewScriptBlockID);

				var tinyMCE = $("#" + tinymce.activeEditor.id + "_parent");
				var activeEditorScriptBlock = tinyMCE.closest(".scriptBlock");
				var activeEditorScriptBlockID = activeEditorScriptBlock.attr("scriptblockid");

				if (activeEditorScriptBlockID == response.NewScriptBlockID) {
					tinymce.activeEditor.setContent("New script.");
				}
			}



			$(".needsSaved").fadeOut();

			$("#txtScriptTitle").attr("originalvalue", $("#txtScriptTitle").val());
		}
		else {
			alert(response.ErrorMessage);
		}
	}

	var onError = function (jqXHR, textStatus, errorThrown) {
		alert("Script failed to save. Please try again.\n if saving continues to fail then please report it.\n\nError: " + errorThrown);
	}



	$.ajax({
		url: "AJAX/AdminScriptEditor.asp?method=SaveScript",
		data: {
			scriptID: scriptID,
			category: category,
			title: title
		},
		type: "POST",
		success: onSuccess,
		error: onError
	});
}

/*----------------------------------------------------------------------*/
/* CREATE BREADCRUMB */
AdminScriptEditor.CreateBreadCrumb = function(breadcrumb){
	var breadCrumb = 		$(breadcrumb);
	var decisions = 		breadCrumb.parents("li.scriptDecision");
	var decisionTitles = 	[];
	var breadCrumbText = 	"";
	
	for(var x = 0, len = decisions.length; x < len; x++){
		var curDecision = $(decisions[x]);
		var title = curDecision.find("> .decisionTitle");
		var titleInput = title.find("input");
		if(titleInput.length > 0){
		    var titleText = titleInput.val();
		}
		else{
		    var titleText = title.text();
		}
		
		decisionTitles.push(titleText);
	}
	
	for(var x = 0, len = decisionTitles.length; x < len; x++){
		breadCrumbText += decisionTitles.pop();
		
		if(x+1 != len){
			breadCrumbText += " > ";
		}
	}
	
	
	return "path: " + breadCrumbText;
};

/*----------------------------------------------------------------------*/
/* CREATE BREADCRUMB CHAIN */
AdminScriptEditor.CreateBreadCrumbChain = function(topLevelDecision){
    var decisions = topLevelDecision.add(topLevelDecision.find("li.scriptDecision:not(.addNew)"));
    
    for(var x = 0, len = decisions.length; x < len; x++){
        var curDecision = $(decisions[x]);
        var curBreadCrumb = curDecision.find(".breadCrumb:first");
        
        var newBreadCrumb = AdminScriptEditor.CreateBreadCrumb(curBreadCrumb);
        curBreadCrumb.text(newBreadCrumb);
    }
}

/*----------------------------------------------------------------------*/
/* SET HASCHANGES */
AdminScriptEditor.SetHasChanges = function(flag, what){
    AdminScriptEditor.HasChanges = flag;

    switch(what){
        case "script":
            if(flag){
                $("div.scriptMenu span.needsSaved").fadeIn();
            }
            else{
                $("div.scriptMenu span.needsSaved").fadeOut();
            }
            
            break;
            
        case "tinymce":
            if(flag){
                var tinyMCE = $("#" + tinymce.activeEditor.id + "_parent");
                var siblings = tinyMCE.siblings(".scriptBlockMenu");
                var needsSaved = siblings.find("span.needsSaved");
                needsSaved.fadeIn();
            }
            else{
                var tinyMCE = $("#" + tinymce.activeEditor.id + "_parent");
                var siblings = tinyMCE.siblings(".scriptBlockMenu");
                var needsSaved = siblings.find("span.needsSaved");
                needsSaved.fadeOut();           
            }
        
        break;
    }
}


/*----------------------------------------------------------------*/
$(document).ready(function(){
	AdminScriptEditor.Init();
	AdminScriptEditor.InitHandlers();
});